<template>
  <div class="device-detail">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>设备详情</span>
          <div>
            <el-button @click="goBack">返回</el-button>
            <el-button type="primary" @click="refreshDevice">刷新</el-button>
          </div>
        </div>
      </template>
      
      <div v-loading="loading">
        <!-- 基本信息 -->
        <el-descriptions :column="2" border>
          <el-descriptions-item label="设备ID">{{ device.id }}</el-descriptions-item>
          <el-descriptions-item label="设备名称">{{ device.name }}</el-descriptions-item>
          <el-descriptions-item label="设备型号">{{ device.model }}</el-descriptions-item>
          <el-descriptions-item label="序列号">{{ device.serial_number }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(device.status)">
              {{ getStatusText(device.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="绑定用户">{{ device.user_nickname || '未绑定' }}</el-descriptions-item>
          <el-descriptions-item label="固件版本">{{ device.firmware_version }}</el-descriptions-item>
          <el-descriptions-item label="硬件版本">{{ device.hardware_version }}</el-descriptions-item>
          <el-descriptions-item label="电量">
            <el-progress
              :percentage="device.battery_level || 0"
              :color="getBatteryColor(device.battery_level)"
              :stroke-width="10"
              text-inside
            />
          </el-descriptions-item>
          <el-descriptions-item label="信号强度">{{ device.signal_strength }}%</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(device.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="最后心跳">{{ formatDate(device.last_heartbeat) }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 实时状态 -->
        <el-card style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>实时状态</span>
              <el-button type="primary" size="small" @click="refreshDevice">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="status-item">
                <div class="status-label">电流强度</div>
                <div class="status-value">{{ formatIntensity(device.current_intensity) }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="status-item">
                <div class="status-label">频率</div>
                <div class="status-value">{{ formatFrequency(device.current_frequency) }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="status-item">
                <div class="status-label">治疗状态</div>
                <div class="status-value">
                  <el-tag :type="getTreatmentStatusType(device.treatment_status)">
                    {{ getTreatmentStatusText(device.treatment_status) }}
                  </el-tag>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
        
        <!-- 操作面板 -->
        <el-card style="margin-top: 20px;">
          <template #header>
            <span>设备操作</span>
          </template>
          <div class="device-actions">
            <el-button 
              type="primary" 
              :disabled="device.status !== 'online'"
              @click="remoteControl"
            >
              <el-icon><Operation /></el-icon>
              远程控制
            </el-button>
            <el-button 
              type="warning" 
              :disabled="device.status !== 'online'"
              @click="sendCommand('reboot')"
            >
              <el-icon><RefreshRight /></el-icon>
              重启设备
            </el-button>
            <el-button 
              type="danger" 
              @click="disconnectDevice"
            >
              <el-icon><SwitchButton /></el-icon>
              断开连接
            </el-button>
            <el-button @click="exportDeviceData">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
        </el-card>
        
        <!-- 历史记录 -->
        <el-card style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>历史记录</span>
              <el-tabs v-model="activeHistoryTab" size="small">
                <el-tab-pane label="治疗记录" name="treatments"></el-tab-pane>
                <el-tab-pane label="设备日志" name="logs"></el-tab-pane>
              </el-tabs>
            </div>
          </template>
          
          <!-- 治疗记录 -->
          <div v-if="activeHistoryTab === 'treatments'">
            <el-table :data="treatmentRecords" style="width: 100%">
              <el-table-column prop="user_nickname" label="用户" width="120" />
              <el-table-column prop="mode" label="治疗模式" width="120">
                <template #default="{ row }">
                  <el-tag :type="getModeType(row.mode)">
                    {{ getModeText(row.mode) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="start_time" label="开始时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.start_time) }}
                </template>
              </el-table-column>
              <el-table-column prop="duration" label="持续时间" width="120">
                <template #default="{ row }">
                  {{ formatDuration(row.duration) }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getStatusType(row.status)">
                    {{ getStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button size="small" type="primary" @click="viewTreatmentDetail(row.id)">
                    详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 设备日志 -->
          <div v-if="activeHistoryTab === 'logs'">
            <el-table :data="deviceLogs" style="width: 100%">
              <el-table-column prop="timestamp" label="时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.timestamp) }}
                </template>
              </el-table-column>
              <el-table-column prop="level" label="级别" width="100">
                <template #default="{ row }">
                  <el-tag :type="getLogLevelType(row.level)">
                    {{ row.level }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="message" label="消息" />
            </el-table>
          </div>
        </el-card>
      </div>
    </el-card>
    
    <!-- 远程控制对话框 -->
    <RemoteControlDialog
      v-model="showRemoteControl"
      :device="device"
      @command="handleDeviceCommand"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh,
  RefreshRight,
  Operation,
  SwitchButton,
  Download
} from '@element-plus/icons-vue'
import RemoteControlDialog from '@/components/devices/RemoteControlDialog.vue'
import { getDeviceDetail, sendDeviceCommand, disconnectDevice } from '@/api/device'
import {
  formatDate,
  formatDuration,
  formatIntensity,
  formatFrequency
} from '@/utils/format'

interface Device {
  id: string
  name: string
  model: string
  serial_number: string
  status: string
  user_nickname: string
  firmware_version: string
  hardware_version: string
  battery_level: number
  signal_strength: number
  current_intensity: number
  current_frequency: number
  treatment_status: string
  created_at: string
  last_heartbeat: string
}

interface TreatmentRecord {
  id: string
  user_nickname: string
  mode: string
  start_time: string
  duration: number
  status: string
}

interface DeviceLog {
  id: number
  timestamp: string
  level: string
  message: string
}

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const activeHistoryTab = ref('treatments')
const showRemoteControl = ref(false)

const device = ref<Device>({
  id: '',
  name: '',
  model: '',
  serial_number: '',
  status: 'offline',
  user_nickname: '',
  firmware_version: '',
  hardware_version: '',
  battery_level: 0,
  signal_strength: 0,
  current_intensity: 0,
  current_frequency: 0,
  treatment_status: '',
  created_at: '',
  last_heartbeat: ''
})

const treatmentRecords = ref<TreatmentRecord[]>([])
const deviceLogs = ref<DeviceLog[]>([])

const goBack = () => {
  router.go(-1)
}

const loadDeviceDetail = async () => {
  const deviceId = route.params.id as string
  if (!deviceId) {
    ElMessage.error('设备ID无效')
    return
  }
  
  loading.value = true
  try {
    // 获取设备详情
    const response = await getDeviceDetail(deviceId)
    device.value = response.data
    
    // 模拟获取治疗记录
    treatmentRecords.value = [
      {
        id: '1',
        user_nickname: '张三',
        mode: 'mode_a',
        start_time: '2023-05-15T10:30:00Z',
        duration: 1800,
        status: 'completed'
      },
      {
        id: '2',
        user_nickname: '李四',
        mode: 'mode_b',
        start_time: '2023-05-16T14:20:00Z',
        duration: 1200,
        status: 'completed'
      }
    ]
    
    // 模拟获取设备日志
    deviceLogs.value = [
      {
        id: 1,
        timestamp: '2023-05-16T15:30:00Z',
        level: 'info',
        message: '设备连接成功'
      },
      {
        id: 2,
        timestamp: '2023-05-16T14:25:00Z',
        level: 'info',
        message: '治疗完成'
      },
      {
        id: 3,
        timestamp: '2023-05-16T14:20:00Z',
        level: 'info',
        message: '开始治疗'
      }
    ]
  } catch (error) {
    ElMessage.error('获取设备详情失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const refreshDevice = () => {
  loadDeviceDetail()
}

const remoteControl = () => {
  showRemoteControl.value = true
}

const sendCommand = async (command: string) => {
  try {
    await ElMessageBox.confirm(`确定要发送 "${command}" 命令到设备吗？`, '确认操作', {
      type: 'warning'
    })
    
    await sendDeviceCommand(device.value.id, command)
    ElMessage.success('命令发送成功')
    refreshDevice()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('命令发送失败')
      console.error(error)
    }
  }
}

const handleDisconnectDevice = async () => {
  try {
    await ElMessageBox.confirm('确定要断开该设备的连接吗？', '提示', {
      type: 'warning'
    })
    
    await disconnectDevice(device.value.id)
    ElMessage.success('设备已断开连接')
    router.push('/devices/list')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('断开设备连接失败')
      console.error(error)
    }
  }
}

const exportDeviceData = () => {
  ElMessage.success('开始导出设备数据')
  // 这里应该调用API导出设备数据
}

const handleDeviceCommand = async (command: string, params?: any) => {
  try {
    await sendDeviceCommand(device.value.id, command, params)
    ElMessage.success('命令发送成功')
    refreshDevice()
  } catch (error) {
    ElMessage.error('命令发送失败')
    console.error(error)
  }
}

const viewTreatmentDetail = (treatmentId: string) => {
  router.push(`/treatments/detail/${treatmentId}`)
}

// 辅助方法
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    online: 'success',
    offline: 'danger',
    maintenance: 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    online: '在线',
    offline: '离线',
    maintenance: '维护中'
  }
  return texts[status] || status
}

const getBatteryColor = (level: number) => {
  if (level > 50) return '#67c23a'
  if (level > 20) return '#e6a23c'
  return '#f56c6c'
}

const getTreatmentStatusType = (status: string) => {
  const types: Record<string, string> = {
    running: 'primary',
    paused: 'warning',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

const getTreatmentStatusText = (status: string) => {
  const texts: Record<string, string> = {
    running: '治疗中',
    paused: '已暂停',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || status
}

const getModeType = (mode: string) => {
  const types: Record<string, string> = {
    mode_a: 'primary',
    mode_b: 'success',
    mode_c: 'warning'
  }
  return types[mode] || 'info'
}

const getModeText = (mode: string) => {
  const texts: Record<string, string> = {
    mode_a: '模式A',
    mode_b: '模式B',
    mode_c: '模式C'
  }
  return texts[mode] || mode
}

const getLogLevelType = (level: string) => {
  const types: Record<string, string> = {
    error: 'danger',
    warn: 'warning',
    info: 'primary',
    debug: 'success'
  }
  return types[level.toLowerCase()] || 'info'
}

onMounted(() => {
  loadDeviceDetail()
})
</script>

<style scoped lang="scss">
.device-detail {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .status-item {
    text-align: center;
    padding: 20px 0;
    
    .status-label {
      font-size: 14px;
      color: #606266;
      margin-bottom: 8px;
    }
    
    .status-value {
      font-size: 18px;
      font-weight: 500;
      color: #303133;
    }
  }
  
  .device-actions {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }
  
  :deep(.el-descriptions__label) {
    width: 120px !important;
  }
}
</style>